import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/modules/authStore.js'

// 图标名称标准化函数 (与authStore中的保持一致)
const normalizeIconName = (icon) => {
    if (!icon) return 'default'
    return icon.toString()
        .toLowerCase()
        .replace(/^icon-?/, '')
        .replace(/-?icon$/, '')
        .replace(/\s+/g, '-')
        .trim()
}

// 基础路由配置
const baseRoutes = [
    {
        path: '/',
        redirect: '/dashboard',
        component: () => import('@/components/layout/Layout.vue'),
        meta: {
            requiresAuth: true,
            icon: normalizeIconName('dashboard') // 添加标准化图标
        },
        children: [
            {
                path: '/dashboard',
                name: 'Dashboard',
                component: () => import('@/views/dashboard/Home.vue'),
                meta: {
                    requiresAuth: true,
                    title: '仪表盘',
                    icon: normalizeIconName('dashboard') // 添加标准化图标
                }
            }
        ]
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/auth/LoginView.vue'),
        meta: {
            requiresAuth: false,
            title: '登录'
        }
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('@/views/auth/RegisterView.vue'),
        meta: {
            requiresAuth: false,
            title: '注册'
        }
    },
    {
        path: '/unauthorized',
        name: 'Unauthorized',
        component: () => import('@/views/dashboard/Unauthorized.vue'),
        meta: {
            requiresAuth: false,
            title: '未授权'
        }
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('@/views/dashboard/NotFound.vue'),
        meta: {
            requiresAuth: false,
            title: '页面未找到'
        }
    }
]

// 动态路由配置（与后端菜单对应的路由）
const dynamicRoutes = [
    {
        path: '/system',
        name: 'System',
        component: () => import('@/components/layout/Layout.vue'),
        meta: {
            requiresAuth: true,
            title: '系统管理'
        },

        children: [
                     {
                path:'config',
                name:'SystemConfig',
                component: () => import('@/views/config/configView.vue'),
                meta: {
                    requiresAuth: true,
                    title: '系统配置'
                }

            },
            {
                path: '/system/user',
                name: 'SystemUser',
                component: () => import('@/views/system/User.vue'),
                meta: {
                    requiresAuth: true,
                    title: '用户管理',
                    icon: normalizeIconName('user') // 添加标准化图标
                }
            },
            {
                path: 'role',
                name: 'SystemRole',
                component: () => import('@/views/system/Role.vue'),
                meta: {
                    requiresAuth: true,
                    title: '角色管理'
                }
            },
            {
                path: 'menu',
                name: 'SystemMenu',
                component: () => import('@/views/system/Menu.vue'),
                meta: {
                    requiresAuth: true,
                    title: '菜单管理'
                }
            },
            {
                path: 'dept',
                name: 'SystemDept',
                component: () => import('@/views/system/Dept.vue'),
                meta: {
                    requiresAuth: true,
                    title: '部门管理'
                }
            },
            {
                path: 'acl',
                name: 'SystemAcl',
                component: () => import('@/views/system/Acl.vue'),
                meta: {
                    requiresAuth: true,
                    title: '权限管理'
                }
            }
        ]
    },
    {
        path: '/lawyer',
        name: 'Lawyer',
        component: () => import('@/components/layout/Layout.vue'),
        meta: {
            requiresAuth: true,
            title: '律师管理'
        },
        children: [
            {
                path:'lawyerinfo',
                name:'LawyerInfo',
                component: () => import('@/views/lawyer/LawyerInfo.vue'),
                meta: {
                    requiresAuth: true,
                    title: '律师信息'
                }
            },
            {
                path:'audit',
                name:'LawyerAudit',
                component: () => import('@/views/lawyer/audit.vue'),
                meta: {
                    requiresAuth: true,
                    title: '律师审核'
                }
            },
            {
                path:'performance',
                name:'LawyerPerformance',
                component: () => import('@/views/lawyer/performance.vue'),
                meta: {
                    requiresAuth: true,
                    title: '律师绩效'
                }
            },
        ]
    },
    {
        path: '/case',
        name: 'Case',
        component: () => import('@/components/layout/Layout.vue'),
        meta: {
            requiresAuth: true,
        },
        children: [
            {
                path: '',
                name: '',
                component: () => import('@/views/cases/operateCase.vue'),
                meta: {
                    requiresAuth: true,
                    title: '案件管理'
                }
            }
        ]
    },
    {
        path: '/ai',
        name: 'AiChat',
        component: () => import('@/components/layout/Layout.vue'),
        meta: {
            requiresAuth: true,
        },
        children: [
            {
                path: '',
                name: '',
                component: () => import('@/views/AiChat/Index.vue'),
                meta: {
                    requiresAuth: true,
                    title: 'AI法律咨询'
                }
            }
        ]
    },
    {
        path: '/cesium',
        name: 'Cesium',
        component: () => import('@/components/layout/Layout.vue'),
        meta: {
            requiresAuth: true,
        },
        children: [
            {
                path: '',
                name: '',
                component: () => import('@/views/cesium/index.vue'),
                meta: {
                    requiresAuth: true,
                    title: 'Cesium地图'
                }
            }
        ]
    },
    {
        path: '/log',
        name: 'Log',
        component: () => import('@/components/layout/Layout.vue'),
        meta: {
            requiresAuth: true,
        },
        children: [
            {
                path: '',
                name: '',
                component: () => import('@/views/Log/LogList.vue'),
                meta: {
                    requiresAuth: true,
                    title: '日志管理'
                }
            }
        ]
    },
    {
        path: '/persionalcenter',
        name: 'Profile',
        component: () => import('@/components/layout/Layout.vue'),
        meta: {
            requiresAuth: true,
        },
        children: [
            {
                path: '',
                name: '',
                component: () => import('@/views/persionalcenter/index.vue'),
                meta: {
                    requiresAuth: true,
                    title: '个人中心'
                }
            }
        ]
    },
    {
        path: '/chatsimple',
        name: 'ChatSimple',
        component: () => import('@/components/layout/Layout.vue'),
        meta: {
            requiresAuth: true,
        },
        children: [
            {
                path: '',
                name: '',
                component: () => import('@/components/ChatSimple.vue'),
                meta: {
                    requiresAuth: true,
                    title: 'STOMP测试'
                }
            }
        ]
    },
    {
        path: '/realname',
        name: 'RealnameRegistration',
        component: () => import('@/components/layout/Layout.vue'),
        meta: {
            requiresAuth: true,
        },
        children: [
            {
                path: '',
                name: '',
                component: () => import('@/views/realname-registration/Realname.vue'),
                meta: {
                    requiresAuth: true,
                    title: '实名管理'
                }
            }
        ]
    },
    {
        path: '/chat',
        name: 'Chat',
        component: () => import('@/components/layout/Layout.vue'),
        meta: {
            requiresAuth: true,
        },
        children: [
            {
                path: 'chatapp',
                name: 'ChatApp',
                component: () => import('@/views/chat/ChatApp.vue'),
                meta: {
                    requiresAuth: true,
                    title: '迅联平台'
                },
                children: [
                    {
                        path: 'chatwindow',
                        name: 'ChatWindow',
                        component: () => import('@/views/chat/ChatWindow.vue'),
                        meta: {
                            requiresAuth: true,
                            title: '聊天窗口'
                        }
                    },
                    {
                        path: 'friendsidebar',
                        name: 'FriendSidebar',
                        component: () => import('@/views/chat/FriendSidebar.vue'),
                        meta: {
                            requiresAuth: true,
                            title: '好友侧边栏'
                        }
                    }
                ]
            }
        ]
    },
        {
        path: '/applyCase',
        name: 'ApplyCase',
        component: () => import('@/components/layout/Layout.vue'),
        meta: {
            requiresAuth: true,
        },
        children: [
            {
                path: '',
                name: '',
                component: () => import('@/views/applyCase/ApplyCase.vue'),
                meta: {
                    requiresAuth: true,
                    title: '申请援助'
                }

            }
        ]
    }
     

]



// 创建路由实例
const router = createRouter({
    history: createWebHistory(),
    strict: false, // 关闭严格模式
    routes: [...baseRoutes, ...dynamicRoutes].map(route => {
        // 确保所有路由的meta.icon都经过标准化
        if (route.meta) {
            route.meta.icon = normalizeIconName(route.meta.icon)
        }
        if (route.children) {
            route.children = route.children.map(child => {
                if (child.meta) {
                    child.meta.icon = normalizeIconName(child.meta.icon)
                }
                return child
            })
        }
        return route
    }),
    linkActiveClass: "router-link-active",
    linkExactActiveClass: "router-link-exact-active"
})

// 导航守卫
router.beforeEach(async (to, from, next) => {
    const authStore = useAuthStore()

    // 设置页面标题
    if (to.meta.title) {
        document.title = to.meta.title
    }

    // 检查路由是否需要认证
    if (to.matched.some(record => record.meta.requiresAuth)) {
        if (!authStore.isAuthenticated()) {
            console.log('未登录，重定向到登录页')
            next('/login')
        } else {
            // 检查用户是否有权限访问该路由
            const hasPermission = authStore.menuList.some(menu => {
                return menu.path === to.path ||
                    (menu.children && menu.children.some(child => child.path === to.path))
            })

            if (hasPermission || to.path === '/dashboard') {
                next()
            } else {
                console.warn('无权限访问:', to.path)
                next('/unauthorized')
            }
        }
    } else {
        next()
    }
})
export default router